package com.sjsu.CMPE226.etl.dataloader;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.sjsu.CMPE226.etl.beans.Observation;
import com.sjsu.CMPE226.etl.beans.Station;

import com.sjsu.CMPE226.Hibernate.config.LocationHash;

public class ShardedORMDataLoader{

	public int loadStationsBatch(List<Station> stationList)
	{
		long st = System.currentTimeMillis();
		LocationHash location = new LocationHash(2);
		Session[] slist = location.allLocations();
		
		for (Session session : slist) 
		{
		try {
			session.beginTransaction();
			for (Station station : stationList) 
				{
				session.save(station);
					
				if (stationList.size() % 1000 == 0) {
					session.flush();
					session.clear();
				}
				}
			session.getTransaction().commit();
			} catch (RuntimeException e) {
				session.getTransaction().rollback();
				//throw e;
			}
			finally {
				// session.close();
			}
		}
		long et = System.currentTimeMillis();
		System.out.println("Time to load data through ORM in SHARDED DB in 'Station' Table:"+ (et - st) + " msec");
		return 1;
		}
		

		public int loadObservationsBatch(List<Observation> observationList) 
		{
			long st = System.currentTimeMillis();
			Session session = null;
			int n = 0;
				for (Observation observation : observationList) 
				{
					n++;
					//System.out.println("n: " + n);
					if (observation.getDatetime() == null) 
					{

					} 
					else 
					{
						LocationHash location = new LocationHash(2);
						session = location.locate(observation.getDatetime());
						Transaction tx = session.beginTransaction();
						try {
							session.save(observation);
							if (n % 1000 == 0) {
								session.flush();
								session.clear();
							}
							tx.commit();
						} catch (RuntimeException e) {
							session.getTransaction().rollback();
							System.out.println("Exception while loading object!");
							e.printStackTrace();
							//throw e;
						}
					}
				}
				long et = System.currentTimeMillis();
				System.out.println("Time to load data through ORM in SHARDED DB in 'Observation' Table:"+ (et - st) + " msec");
		return 1;
		}
}